# -*-coding:utf-8 -*-
'''
Created on 2011-10-30

@author: tony.li.fly@gmail.com
'''
from xyh.oa.models import Orders,User,OrderHbl,OrderMbl,Bill
from django.http import HttpResponse
from django.utils import simplejson as json
from xyh.oa.utils.utils import Encoder
from xyh.oa.utils.export_report import write_bill,write_hbl_international,write_hbl
import datetime,time
from django.db.models import Count
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def generate():
    today = datetime.datetime.today()
    monthCount = Orders.objects.filter(insert_date__gte=datetime.datetime(today.year,today.month,1)).aggregate(Count('id'))['id__count']
    return 'SLL' + time.strftime("%Y%m", time.localtime()) + ('%03d' % (monthCount + 1))

def listall(request):
    result = []
    allList = Orders.objects.order_by('-insert_date')
    
    order_code =  request.GET.get('order_code','')
    if order_code.strip() != '':
        allList = allList.filter(order_code__istartswith = order_code.strip())
      
    saleman =  request.GET.get('saleman','')
    if saleman.strip() != '':
        allList = allList.filter(saleman__id__exact = saleman.strip())  
    
    client_code =  request.GET.get('client_code','')
    if client_code.strip() != '':
        allList = allList.filter(client_code__exact = client_code.strip())
        
    booking_date =  request.GET.get('booking_date','')
    if booking_date.strip() != '':
        allList = allList.filter(booking_date__exact = booking_date.strip())
    
    h_release_way =  request.GET.get('h_release_way','')
    if h_release_way.strip() != '':
        allList = allList.filter(h_release_way__exact = h_release_way.strip())
        
    m_release_way =  request.GET.get('m_release_way','')
    if m_release_way.strip() != '':
        allList = allList.filter(m_release_way__exact = m_release_way.strip())
    
    container_info =  request.GET.get('container_info','')
    if container_info.strip() != '':
        allList = allList.filter(container_info__contains = container_info.strip())
    
    allList = allList.all()
    paginator = Paginator(allList, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        pageList = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pageList = paginator.page(paginator.num_pages)
    for c in pageList.object_list:
        result.append({'id':c.id, 'order_code':c.order_code, 'client_company':c.client_company, 'booking_date':c.booking_date, 'shipping_date':c.shipping_date
                       , 'saleman_name':c.saleman.name, 'operator_name':c.operator.name, 'h_release_way':c.h_release_way})
    result = {'count':paginator.count,'rows':result};
    return HttpResponse(json.dumps(result, cls=Encoder))


def delOrder(request, order_id):
    order = Orders.objects.get(pk=order_id)
    order.delete()
    return HttpResponse()
    
def addOrder(request):
    order = Orders()
    order.order_code = generate()
    order.container_type = request.POST['container_type']
    order.saleman = User.objects.get(pk=request.POST['saleman'])
    order.operator = request.session['user']
    order.client_code = request.POST['client_code']
    order.client_company = request.POST['client_company']
    order.client_person = request.POST['client_person']
    order.client_phone = request.POST['client_phone']
    order.client_fax = request.POST['client_fax']
    order.cargo_collection_type = request.POST['cargo_collection_type']
    order.cargo_collection_code = request.POST.get('cargo_collection_code',None)
    order.cargo_collection_name = request.POST.get('cargo_collection_name',None)
    order.shipper = request.POST['shipper']
    order.consignee = request.POST['consignee']
    order.notifier = request.POST['notifier']
    order.receipt_place = request.POST.get('receipt_place',None)
    order.loading_port = request.POST.get('loading_port',None)
    order.unloading_port = request.POST.get('unloading_port',None)
    order.destination_port = request.POST.get('destination_port',None)
    order.destination_place = request.POST.get('destination_place',None)
    order.container_info = request.POST.get('container_info',None)
    condition = request.POST.get('large_number',None)
    order.large_number = None if condition =='' else condition
    order.large_packing_type = request.POST.get('large_packing_type',None)
    condition = request.POST.get('small_number',None)
    order.small_number = None if condition =='' else condition
    order.small_packing_type = request.POST.get('small_packing_type',None)
    condition = request.POST.get('gross_weight',None)
    order.gross_weight = None if condition =='' else condition
    condition = request.POST.get('volume',None)
    order.volume = None if condition =='' else condition
    order.chinese_name = request.POST.get('chinese_name',None)
    order.english_name = request.POST.get('english_name',None)
    order.shipping_mark = request.POST.get('shipping_mark',None)
    order.info_summy = request.POST.get('info_summy',None)
    condition = request.POST.get('booking_date',False)
    if condition:
        order.booking_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    condition = request.POST.get('shipping_date',False)
    if condition:
        order.shipping_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    condition = request.POST.get('arrival_date',False)
    if condition:
        order.arrival_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    order.m_payment_type = request.POST.get('m_payment_type',None)
    order.h_payment_type = request.POST.get('h_payment_type',None)
    order.shipping_company_code = request.POST.get('shipping_company_code',None)
    order.shipping_company_name = request.POST.get('shipping_company_name',None)
    order.shipping_company_person = request.POST.get('shipping_company_person',None)
    order.shipping_company_phone = request.POST.get('shipping_company_phone',None)
    order.shipping_company_fax = request.POST.get('shipping_company_fax',None)
    order.booking_proxy_company_code = request.POST.get('booking_proxy_company_code',None)
    order.booking_proxy_company_name = request.POST.get('booking_proxy_company_name',None)
    order.booking_proxy_company_person = request.POST.get('booking_proxy_company_person',None)
    order.booking_proxy_company_phone = request.POST.get('booking_proxy_company_phone',None)
    order.booking_proxy_company_fax = request.POST.get('booking_proxy_company_fax',None)
    order.h_release_way = request.POST.get('h_release_way',None)
    order.m_release_way = request.POST.get('m_release_way',None)
    order.remark = request.POST.get('remark',None)
    order.status = 1 #1:操作中
    order.insert_date = datetime.datetime.now()
    order.update_date = datetime.datetime.now()
    order.save()
    
    #保存HB/L
    orderHbl = OrderHbl()
    orderHbl.order = order
    orderHbl.shipper = order.shipper
    orderHbl.notifier = order.notifier
    orderHbl.consignee = order.consignee
    orderHbl.cargo_collection_name = order.cargo_collection_name
    orderHbl.shipping_date = order.shipping_date
    orderHbl.receipt_place = order.receipt_place
    orderHbl.loading_port = order.loading_port
    orderHbl.unloading_port = order.unloading_port
    orderHbl.destination_port = order.destination_port
    orderHbl.destination_place = order.destination_place
    orderHbl.container_info = order.container_info
    orderHbl.info_summy = order.info_summy
    orderHbl.gross_weight = order.gross_weight
    orderHbl.volume = order.volume
    orderHbl.consignee = order.consignee
    orderHbl.consignee = order.consignee
    orderHbl.consignee = order.consignee
    orderHbl.consignee = order.consignee
    orderHbl.consignee = order.consignee
    orderHbl.save()
    #保存HB/L
    orderMbl = OrderMbl()
    orderMbl.order = order
    orderMbl.shipper = order.shipper
    orderMbl.notifier = order.notifier
    orderMbl.consignee = order.consignee
    orderMbl.cargo_collection_name = order.cargo_collection_name
    orderMbl.shipping_date = order.shipping_date
    orderMbl.receipt_place = order.receipt_place
    orderMbl.loading_port = order.loading_port
    orderMbl.unloading_port = order.unloading_port
    orderMbl.destination_port = order.destination_port
    orderMbl.destination_place = order.destination_place
    orderMbl.container_info = order.container_info
    orderMbl.info_summy = order.info_summy
    orderMbl.gross_weight = order.gross_weight
    orderMbl.volume = order.volume
    orderMbl.consignee = order.consignee
    orderMbl.consignee = order.consignee
    orderMbl.consignee = order.consignee
    orderMbl.consignee = order.consignee
    orderMbl.consignee = order.consignee
    orderMbl.save()
    
    return HttpResponse()

def updateOrder(request):
    order = Orders.objects.get(pk=request.POST['id'])
    order.container_type = request.POST['container_type']
    order.saleman = User.objects.get(pk=request.POST['saleman'])
#    order.operator = request.session['user']
    order.client_code = request.POST['client_code']
    order.client_company = request.POST['client_company']
    order.client_person = request.POST['client_person']
    order.client_phone = request.POST['client_phone']
    order.client_fax = request.POST['client_fax']
    order.cargo_collection_type = request.POST['cargo_collection_type']
    order.cargo_collection_code = request.POST.get('cargo_collection_code',None)
    order.cargo_collection_name = request.POST.get('cargo_collection_name',None)
    order.shipper = request.POST['shipper']
    order.consignee = request.POST['consignee']
    order.notifier = request.POST['notifier']
    order.receipt_place = request.POST.get('receipt_place',None)
    order.loading_port = request.POST.get('loading_port',None)
    order.unloading_port = request.POST.get('unloading_port',None)
    order.destination_port = request.POST.get('destination_port',None)
    order.destination_place = request.POST.get('destination_place',None)
    order.container_info = request.POST.get('container_info',None)
    condition = request.POST.get('large_number',None)
    order.large_number = None if condition =='' else condition
    order.large_packing_type = request.POST.get('large_packing_type',None)
    condition = request.POST.get('small_number',None)
    order.small_number = None if condition =='' else condition
    order.small_packing_type = request.POST.get('small_packing_type',None)
    condition = request.POST.get('gross_weight',None)
    order.gross_weight = None if condition =='' else condition
    condition = request.POST.get('volume',None)
    order.volume = None if condition =='' else condition
    order.chinese_name = request.POST.get('chinese_name',None)
    order.english_name = request.POST.get('english_name',None)
    order.shipping_mark = request.POST.get('shipping_mark',None)
    order.info_summy = request.POST.get('info_summy',None)
    condition = request.POST.get('booking_date',False)
    if condition:
        order.booking_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    condition = request.POST.get('shipping_date',False)
    if condition:
        order.shipping_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    condition = request.POST.get('arrival_date',False)
    if condition:
        order.arrival_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    order.m_payment_type = request.POST.get('m_payment_type',None)
    order.h_payment_type = request.POST.get('h_payment_type',None)
    order.shipping_company_code = request.POST.get('shipping_company_code',None)
    order.shipping_company_name = request.POST.get('shipping_company_name',None)
    order.shipping_company_person = request.POST.get('shipping_company_person',None)
    order.shipping_company_phone = request.POST.get('shipping_company_phone',None)
    order.shipping_company_fax = request.POST.get('shipping_company_fax',None)
    order.booking_proxy_company_code = request.POST.get('booking_proxy_company_code',None)
    order.booking_proxy_company_name = request.POST.get('booking_proxy_company_name',None)
    order.booking_proxy_company_person = request.POST.get('booking_proxy_company_person',None)
    order.booking_proxy_company_phone = request.POST.get('booking_proxy_company_phone',None)
    order.booking_proxy_company_fax = request.POST.get('booking_proxy_company_fax',None)
    order.h_release_way = request.POST.get('h_release_way',None)
    order.m_release_way = request.POST.get('m_release_way',None)
    order.remark = request.POST.get('remark',None)
#    order.status = 1 #1:操作中
#    order.insert_date = datetime.datetime.now()
    order.update_date = datetime.datetime.now()
    order.save()
    return HttpResponse()

def loadOrder(request,order_id):
    order = Orders.objects.get(pk=order_id)
    return HttpResponse(json.dumps(order, cls=Encoder))

def loadHbl(request,order_id):
    order = Orders.objects.get(pk=order_id)
    hbl = OrderHbl.objects.get(order=order)
#    result = {'id':hbl.id,'shipper':hbl.shipper,'consignee':hbl.consignee,'notifier':hbl.notifier,'destination_port_proxy':hbl.destination_port_proxy,'so':hbl.so
#              ,'shipping_date':hbl.shipping_date,'shipping_name_number':hbl.shipping_name_number,'receipt_place':hbl.receipt_place,'loading_port':hbl.loading_port,'unloading_port':hbl.unloading_port
#              ,'destination_port':hbl.destination_port,'destination_place':hbl.destination_place,'transit_clause':hbl.transit_clause,'shipper':hbl.shipper,'shipper':hbl.shipper
#              ,'shipper':hbl.shipper,'shipper':hbl.shipper,'shipper':hbl.shipper,'shipper':hbl.shipper,'shipper':hbl.shipper}
    return HttpResponse(json.dumps(hbl, cls=Encoder))
    
def updateHbl(request):
    #保存HB/L
    orderHbl = OrderHbl.objects.get(pk=request.POST['id'])
    orderHbl.lading_bill_way = request.POST.get('lading_bill_way',None)
    orderHbl.shipper = request.POST.get('shipper',None)
    orderHbl.consignee = request.POST.get('consignee',None)
    orderHbl.notifier = request.POST.get('notifier',None)
    orderHbl.cargo_collection_name = request.POST.get('cargo_collection_name',None)
    orderHbl.so = request.POST.get('so',None)
    condition = request.POST.get('shipping_date',False)
    if condition:
        orderHbl.shipping_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    
    orderHbl.shipping_name_number = request.POST.get('shipping_name_number',None)
    orderHbl.receipt_place = request.POST.get('receipt_place',None)
    orderHbl.loading_port = request.POST.get('loading_port',None)
    orderHbl.unloading_port = request.POST.get('unloading_port',None)
    orderHbl.destination_port = request.POST.get('destination_port',None)
    orderHbl.destination_place = request.POST.get('destination_place',None)
    orderHbl.transit_clause = request.POST.get('transit_clause',None)
    
    orderHbl.payment_way = request.POST.get('payment_way',None)
    orderHbl.container_info = request.POST.get('container_info',None)
    orderHbl.fee_description = request.POST.get('fee_description',None)
    orderHbl.info_summy = request.POST.get('info_summy',None)
    condition = request.POST.get('numbers',None)
    orderHbl.numbers = None if condition =='' else condition
    orderHbl.packing_type = request.POST.get('packing_type',None)
    condition = request.POST.get('gross_weight',None)
    orderHbl.gross_weight = None if condition =='' else condition
    condition = request.POST.get('volume',None)
    orderHbl.volume = None if condition =='' else condition
    orderHbl.payment_address = request.POST.get('payment_address',None)
    orderHbl.issue_number = request.POST.get('issue_number',None)
    orderHbl.issue_address = request.POST.get('issue_address',None)
    orderHbl.sealing_number = request.POST.get('sealing_number',None)
    orderHbl.shipping_mark = request.POST.get('shipping_mark',None)
    orderHbl.english_name = request.POST.get('english_name',None)
    condition = request.POST.get('issue_date',False)
    if condition:
        orderHbl.issue_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    
    orderHbl.save()
    return HttpResponse()

def loadMbl(request,order_id):
    order = Orders.objects.get(pk=order_id)
    mbl = OrderMbl.objects.get(order=order)
#    result = {'id':mbl.id,'shipper':mbl.shipper,'consignee':mbl.consignee,'notifier':mbl.notifier,'destination_port_proxy':mbl.destination_port_proxy,'so':mbl.so
#              ,'shipping_date':mbl.shipping_date,'shipping_name_number':mbl.shipping_name_number,'receipt_place':mbl.receipt_place,'loading_port':mbl.loading_port,'unloading_port':mbl.unloading_port
#              ,'destination_port':mbl.destination_port,'destination_place':mbl.destination_place,'transit_clause':mbl.transit_clause,'shipper':mbl.shipper,'shipper':mbl.shipper
#              ,'shipper':mbl.shipper,'shipper':mbl.shipper,'shipper':mbl.shipper,'shipper':mbl.shipper,'shipper':mbl.shipper}
    return HttpResponse(json.dumps(mbl, cls=Encoder))
    
def updateMbl(request):
    #保存HB/L
    orderMbl = OrderMbl.objects.get(pk=request.POST['id'])
    orderMbl.lading_bill_way = request.POST.get('lading_bill_way',None)
    orderMbl.booking_number = request.POST.get('booking_number',None)
    orderMbl.mbl_code = request.POST.get('mbl_code',None)
    orderMbl.shipper = request.POST.get('shipper',None)
    orderMbl.consignee = request.POST.get('consignee',None)
    orderMbl.notifier = request.POST.get('notifier',None)
    orderMbl.cargo_collection_name = request.POST.get('cargo_collection_name',None)
    orderMbl.so = request.POST.get('so',None)
    condition = request.POST.get('shipping_date',False)
    if condition:
        orderMbl.shipping_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    
    orderMbl.shipping_name_number = request.POST.get('shipping_name_number',None)
    orderMbl.receipt_place = request.POST.get('receipt_place',None)
    orderMbl.loading_port = request.POST.get('loading_port',None)
    orderMbl.unloading_port = request.POST.get('unloading_port',None)
    orderMbl.destination_port = request.POST.get('destination_port',None)
    orderMbl.destination_place = request.POST.get('destination_place',None)
    orderMbl.transit_clause = request.POST.get('transit_clause',None)
    
    orderMbl.payment_way = request.POST.get('payment_way',None)
    orderMbl.container_info = request.POST.get('container_info',None)
    orderMbl.fee_description = request.POST.get('fee_description',None)
    orderMbl.info_summy = request.POST.get('info_summy',None)
    condition = request.POST.get('numbers',None)
    orderMbl.numbers = None if condition =='' else condition
    orderMbl.packing_type = request.POST.get('packing_type',None)
    condition = request.POST.get('gross_weight',None)
    orderMbl.gross_weight = None if condition =='' else condition
    condition = request.POST.get('volume',None)
    orderMbl.volume = None if condition =='' else condition
    orderMbl.payment_address = request.POST.get('payment_address',None)
    orderMbl.issue_number = request.POST.get('issue_number',None)
    orderMbl.issue_address = request.POST.get('issue_address',None)
    orderMbl.sealing_number = request.POST.get('sealing_number',None)
    orderMbl.shipping_mark = request.POST.get('shipping_mark',None)
    orderMbl.english_name = request.POST.get('english_name',None)
    condition = request.POST.get('issue_date',False)
    if condition:
        orderMbl.issue_date = datetime.datetime.strptime(condition,'%Y-%m-%d')
    
    orderMbl.save()
    return HttpResponse()

def loadBill(request,order_id):
    order = Orders.objects.get(pk=order_id)
    bills = order.bill_set.order_by('bill_code').all()
    result = []
    for bill in bills:
        result.append({'id':bill.id,'order':bill.order.id,'bill_code':bill.bill_code,'bill_name':bill.bill_name,'amount':bill.amount,'count':bill.count,'currency':bill.currency,'total':bill.total,'type':bill.type})
    return HttpResponse(json.dumps(result, cls=Encoder))

def addBill(request):
    bill = Bill()
    bill.order = Orders.objects.get(pk=request.POST['orderId'])
    bill.bill_code = request.POST['bill_code']
    bill.bill_name = request.POST['bill_name']
    bill.amount = request.POST['amount']
    bill.count = request.POST['count']
    
    bill.total = float(request.POST['amount']) *  float(request.POST['count'])
    
    bill.currency = request.POST['currency']
    bill.type = request.POST['type']
    bill.save()
    return HttpResponse()

def delBill(request,bill_id):
    bill = Bill.objects.get(pk=bill_id)
    bill.delete()
    return HttpResponse()

def exportBill(request,order_id):
    order = Orders.objects.get(pk=order_id)
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + str(order.order_code) + '账单.xls'
    write_bill(response,order)
    return response;

def exportHbl(request,order_id):
    order = Orders.objects.get(pk=order_id)
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + str(order.order_code) + 'HBL.xls'
    write_hbl(response,order)
    return response;

def exportHblUsa(request,order_id):
    order = Orders.objects.get(pk=order_id)
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + str(order.order_code) + 'HBL-TLX.xls'
    write_hbl_international(response,order)
    return response;
    